package cn.blogss.tutorial;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @Author: Thatcher Li
 * @Date: 2021/3/18
 * @Descripttion: 添加联系人到地址簿
 */
public class AddPerson {
    public static void main(String[] args) throws IOException {
        if(args.length != 1){
            System.err.println("Usage: AddPerson ADDRESS_BOOK_FILE");
            System.exit(-1);
        }

        AddressBookProto.AddressBook.Builder addressBook = AddressBookProto.AddressBook.newBuilder();
        // Read the existing address book.
        try {
            addressBook.mergeFrom(new FileInputStream(args[0]));
        } catch (IOException e) {
            System.out.println(args[0] + ": File not found. Creating a new file.");
        }

        // Add an address.
        addressBook.addPeople(prompForAddress(new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)),System.out));

        // Write the new address book back to disk.
        FileOutputStream output = new FileOutputStream(args[0]);
        addressBook.build().writeTo(output);
        output.close();
    }

    private static AddressBookProto.Person prompForAddress(BufferedReader stdin, PrintStream stdout) throws IOException {
        AddressBookProto.Person.Builder person = AddressBookProto.Person.newBuilder();

        stdout.print("Enter person ID: ");
        person.setId(Integer.parseInt(stdin.readLine()));

        stdout.print("Enter name: ");
        person.setName(stdin.readLine());

        stdout.print("Enter email address (blank for none): ");
        String email = stdin.readLine();
        if(email.length() > 0){
            person.setEmail(email);
        }

        while(true){
            stdout.print("Enter a phone number (or leave blank to finish): ");
            String number = stdin.readLine();
            if(number.length() == 0){
                break;
            }

            AddressBookProto.Person.PhoneNumber.Builder phoneNumber = AddressBookProto.Person.PhoneNumber.newBuilder();
            phoneNumber.setNumber(number);

            stdout.print("Is this a mobile, home, or work phone? ");
            String type = stdin.readLine();
            if(type.equals("mobile")){
                phoneNumber.setType(AddressBookProto.Person.PhoneType.MOBILE);
            }else if(type.equals("home")){
                phoneNumber.setType(AddressBookProto.Person.PhoneType.HOME);
            }else if(type.equals("work")){
                phoneNumber.setType(AddressBookProto.Person.PhoneType.WORK);
            }

            person.addPhones(phoneNumber);
        }

        return person.build();
    }
}
